// pages/order/orderDetail/orderDetail.js
import getIn from '../../../sdk/utils/getIn';
import { ORDER_TYPE_AUDITE, ORDER_TYPE_UNPAID, ORDER_TYPE_PAID, ORDER_TYPE_COMPLETED, ORDER_TYPE_CANCELED, ORDER_TYPE_CLOSED } from '../../../utils/config'
import {PRICE_DETAIL} from "../../../utils/url";
import { API_ORDER_DETAIL, API_ORDER_CHANGE_STATUS, API_SAVE_FORMID } from "../../../sdk/business/url";
import {showSuccess, showFail} from '../../../utils/util';
import { wxPay } from '../../../utils/orderPay'
import {addNotifier, removeNotifier, notify} from "../../../sdk/utils/NotifyRegistryCenter";
Page({
  /**
   * 页面的初始数据
   */
  data: {
      ORDER_TYPE_AUDITE,
      ORDER_TYPE_UNPAID,
      ORDER_TYPE_PAID,
      ORDER_TYPE_COMPLETED,
      ORDER_TYPE_CANCELED,
      ORDER_TYPE_CLOSED,
      orderDetailObject: {},
      params:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
      const id = getIn(options, ['order_id']);
      const userInfo = getApp().globalData.userInfo;
      this.setData({ 'params.id': id, userInfo }, () => {
          this.fetchData();
      });
      addNotifier && addNotifier('updateorderdetail', this.fetchData, this)
      wx.showLoading({ title: '加载中' });
  },
  // 获取订单数据
  fetchData() {
      const token = wx.getStorageSync('token');
      getApp().userInfo().then((res) => {
        global.request(API_ORDER_DETAIL, { token: res.token, ...this.data.params }, (code, res) => {
              if (code == 'SUCCESS') {
                  wx.hideLoading();
                  const userInfo = getApp().globalData.userInfo;
                  const orderDetailObject = getIn(res, ['data']);
                this.setData({ orderDetailObject, link_products: orderDetailObject.link_products, userInfo })
              } else if (code == 'FAIL') {
                  wx.hideLoading();
              }
          });
      })

  },
    // 跳转费用详情
    toPriceDetail () {
      const { link_products, orderDetailObject: { paid_price, floor_price, order_type, worktime }, params } = this.data;
      const queryString = `link_products=${JSON.stringify(link_products)}&paid_price=${paid_price}&floor_price=${floor_price}&order_type=${order_type}&worktime=${worktime}&id=${params.id}`;
        global.navigateHelper.navigateTo({ pathname: PRICE_DETAIL, queryString });
    },
    // 拨打电话
    makePhone() {
      const { orderDetailObject: { shop, receiver_phone }, userInfo } = this.data;
      const tel = userInfo.member_type_nature ? receiver_phone : shop.tel;
      wx.makePhoneCall({
        phoneNumber: tel
      })
    },
    // 付款
    pay(e) {
        const token = wx.getStorageSync('token');
        const order_id = this.data.params.id;
        const pay_way = 2;
        const trade_type = 'JSAPI';
        const payParams = {
            token, order_id, pay_way, trade_type,
        };
        const form_id = getIn(e.detail, ['formId']);
        global.request(API_SAVE_FORMID, { form_id, token });
        wxPay(payParams, (status, result) => {
            if (status == 'SUCCESS') {
                // 通知刷新订单列表
                showSuccess('支付成功');
                this.fetchData();
                notify('updateorderlist');
            } else if (status == 'PAY_FAIL') {
                showFail('支付失败');
            } else if (status == 'FAIL') {
                showFail(result && result.msg);
            }
        });
    },
    // 取消订单
    cancel(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = this.data.params.id;
        const form_id = getIn(e.detail, ['formId']);
        global.request(API_SAVE_FORMID, { form_id, token });
        wx.showModal({
            title: '确定取消订单？',
            success:(res) => {
                if (res.confirm) {
                    global.request(API_ORDER_CHANGE_STATUS, { token, status: ORDER_TYPE_CANCELED, id }, (code, res) => {
                        if (code == 'SUCCESS') {
                            showSuccess('取消成功');
                            this.fetchData();
                        } else if (code == 'FAIL') {
                            showFail(res.msg);
                        }
                    });
                }
            }
        })
    },
    // 确认订单
    confirm(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = this.data.params.id;
        const form_id = getIn(e.detail, ['formId']);
        global.request(API_SAVE_FORMID, { form_id, token });
        wx.showModal({
            title: '系统提示',
            content: '确认接单后，价格将不能修改，确认继续此操作？',
            success:(res) => {
                if (res.confirm) {
                    global.request(API_ORDER_CHANGE_STATUS, { token, status: ORDER_TYPE_UNPAID, id }, (code, res) => {
                        if (code == 'SUCCESS') {
                            showSuccess('操作成功');
                            this.fetchData();
                        } else if (code == 'FAIL') {
                            showFail(res.msg);
                        }
                    });
                }
            }
        });
    },
    // 完成订单
    complete(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = this.data.params.id;
        const form_id = getIn(e.detail, ['formId']);
        global.request(API_SAVE_FORMID, { form_id, token });
        global.request(API_ORDER_CHANGE_STATUS, { token, status: ORDER_TYPE_COMPLETED, id }, (code, res) => {
            if (code == 'SUCCESS') {
                showSuccess('操作成功');
                this.fetchData();
            } else if (code == 'FAIL') {
                showFail(res.msg);
            }
        });
    },
    // 商家修改订单
    modifyPrice(e) {
        const { link_products, orderDetailObject: { paid_price, floor_price, id } } = this.data;
        const token = wx.getStorageSync('token');
        const queryString = `link_products=${JSON.stringify(link_products)}&paid_price=${paid_price}&floor_price=${floor_price}&id=${id}`;
        const form_id = getIn(e.detail, ['formId']);
        global.request(API_SAVE_FORMID, { form_id, token });
        global.navigateHelper.navigateTo({ pathname: PRICE_DETAIL, queryString });
    },
    // 退款
    refund(e) {
        const token = wx.getStorageSync('token');
        const id = this.data.params.id;
        const form_id = getIn(e.detail, ['formId']);
        global.request(API_SAVE_FORMID, { form_id, token });
        global.request(API_ORDER_CHANGE_STATUS, { token, id, status: ORDER_TYPE_CLOSED }, (code, res) => {
            if (code == 'SUCCESS') {
                showSuccess('操作成功');
                this.fetchData();
            } else if (code == 'FAIL') {
                showFail(res.msg);
            }
        })
    },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    this.fetchData()
  },
    onUnload () {
        removeNotifier && removeNotifier('updateorderdetail', this.fetchData, this)
    },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
  
  }
})